package com.github.cyf.util;

import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**

 * @author chenyifan
 * @create 2024-05-11 19:12
 */
public class HttpResponseUtil {

    /**
     * 获取当前响应
     * 注意在 filter 的 doFilter 方法调用时会返回 null
     * @return
     */
    public static HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }


    /**
     * 响应体写入文本
     * @param response 响应体
     * @param val 数据
     */
    public static void writeText(HttpServletResponse response, Object val) throws IOException {
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("text/plain; charset=utf-8");
        if (Objects.nonNull(val)) {
            PrintWriter writer = response.getWriter();
            writer.write(val.toString());
            writer.flush();
        }
    }

    /**
     * 响应体写入 Json
     * @param response 响应体
     * @param val 数据
     */
    public static void writeJson(HttpServletResponse response, Object val) throws IOException {
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/json; charset=UTF-8");
        if (Objects.nonNull(val)) {
            PrintWriter writer = response.getWriter();
            writer.write(JacksonUtil.toJsonString(val));
            writer.flush();
        }
    }

    /**
     * 设置响应类型为附件
     * @param fileName 客户端下载时的文件名称
     */
    public static void setAttachment(HttpServletResponse response, String fileName) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 设置响应类型为 excel
     * @param fileName 客户端下载时的文件名称
     */
    public static void setExcel(HttpServletResponse response, String fileName) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename='" + URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 设置响应类型为图片
     */
    public static void setImage(HttpServletResponse response) {
        response.setContentType("image/gif");
    }
}